// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import App from "./App";
import router from "./router";
import axios from "axios";
import persistence from "@/lib/persistence";
import pcaa from "@/lib/pcaa";

import "@/lib/canvas-to-blob.min.js";
import upyun from "upyun";

axios.defaults.baseURL = "https://hszx.shop/api/youlegou2";
Vue.config.productionTip = false;
Vue.use(ElementUI);
Vue.prototype.$axios = axios;
Vue.prototype.$persistence = persistence;

Vue.prototype.$findProvince = (province, prokey) => {
  let provinces = [];
  let pros = province[prokey];
  for (let key in pros) {
    if (pros.hasOwnProperty(key)) {
      //港澳台特殊处理
      if (key == "710000" || key == "910000") {
        for (let ky in province[key]) {
          Vue.prototype.$addElement(provinces, province, province[key], ky);
        }
      } else {
        Vue.prototype.$addElement(provinces, province, pros, key);
      }
    }
  }
  return provinces;
};
Vue.prototype.$addElement = (provinces, pros, province, key) => {
  let element = province[key];
  let chs = [];
  let childrens = pros[key];
  //直辖市特殊处理
  if (key == "110000" || key == "120000" || key == "500000" || key == "310000") {
    provinces.push({
      value: key,
      label: element
    });
  } else {
    for (let ky in childrens) {
      if (childrens.hasOwnProperty(ky)) {
        chs.push({
          value: ky,
          label: childrens[ky]
        });
      }
    }
    provinces.push({
      value: key,
      label: element,
      children: chs
    });
  }
  return provinces;
};

// 添加省份数据
Vue.prototype.$province = Vue.prototype.$findProvince(pcaa, "86");
// 添加处理目录方法
Vue.prototype.$findCategory = (list, options) => {
  const opts = options;
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (Vue.prototype.$findItemByValue(opts, item.id)) {
      break;
    }
    if (!item.parentId) {
      opts.push({
        value: item.id,
        label: item.name
      });
    } else {
      for (let j = 0; j < opts.length; j++) {
        const item2 = opts[j];
        const parentOpts = Vue.prototype.$findItemByValue(opts, item.parentId);
        if (parentOpts) {
          parentOpts.children = parentOpts.children || [];
          parentOpts.children.push({
            value: item.id,
            label: item.name
          });
          break;
        }
      }
    }
  }
  return opts;
};

Vue.prototype.$getCategoryNameHander = (options, value) => {
  let name = "";
  let element = Vue.prototype.$findItemByValue(options, value);
  if (element) {
    name = element.label;
  }
  return name;
};

Vue.prototype.$findItemByValue = (objs, value) => {
  for (const item of objs) {
    if (value == item.value) {
      return item;
    }
    if (item.children) {
      for (const child of item.children) {
        const r = Vue.prototype.$findItemByValue([child], value);
        if (r) {
          return r;
        }
      }
    }
  }
};
// 网络通讯方法
Vue.prototype.$axiosPost = (posturl, postarg = null, resfunc = null, errorfunc = null) => {
  Vue.prototype.$axios
    .post(posturl, postarg)
    .then(response => {
      if (response.data.errno) {
        Vue.prototype.$message({
          message: response.data.info,
          type: "error",
          center: true
        });
        return;
      }
      resfunc(response);
    })
    .catch(error => {
      console.log("请求错误---", error);
      errorfunc(error);
    });
};

// 检查图片判断
Vue.prototype.$checkUpload = file => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 4;
  if (!isJPG && !isPNG) {
    Vue.prototype.$message.error("上传头像图片只能是 JPG或者png 格式!");
  }
  if (!isLt2M) {
    Vue.prototype.$message.error("上传头像图片大小不能超过 4MB!");
  }
  return (isJPG || isPNG) && isLt2M;
};

// 登录后清除
Vue.prototype.$clearData = () => {
  //更新session 移除以前数据
  Vue.prototype.$persistence.put("category", null);
};
//生成随机数
Vue.prototype.$randomString = len => {
  len = len || 32;
  var $chars = "qwertyuiopasdfghjklzxcvbnm";
  var maxPos = $chars.length;
  var pwd = "";
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
};

Vue.prototype.$compressImage = (file, defaultSize = 200 * 1024, imageType = "image/jpeg") => {
  var scale = 1;
  if (defaultSize < file.size) {
    scale = (() => {
      return Math.pow(defaultSize / file.size, 0.0625);
    })(); //压缩比的计算
  }
  return new Promise(function(resolve, reject) {
    if (file.size < defaultSize) {
      resolve(new Blob([file]));
    }
    var dataUrl = URL.createObjectURL(file);
    var image = new Image();
    image.crossOrigin = "anonymous";
    image.src = dataUrl;
    image.onload = () => {
      var w = image.width;
      var h = image.height;
      var canvas = document.createElement("canvas");
      canvas.width = w;
      canvas.height = h;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(image, 0, 0, w, h);
      resolve(dataURLtoBlob(canvas.toDataURL(imageType, scale)));
    };
  });
};
Vue.prototype.$signUrl = Vue.prototype.$axios.defaults.baseURL + "/sign/head";
// 开始上传图片文件
Vue.prototype.$starUplodeFile = (data, fileList) => {
  const file = data.file;
  return new Promise((resolve, reject) => {
    //又拍云上传
    var bucket = new upyun.Bucket("chuangjike-img-real");
    var ext = "." + file.name.split(".").pop();
    var fileName = "/hszx/user/" + new Date().getTime() + Vue.prototype.$randomString(32) + ext;
    var client = new upyun.Client(bucket, (bucket, method, path) => {
      var params = "bucket=" + bucket.bucketName + "&method=" + method + "&path=" + path;
      return Vue.prototype.$axios
        .get(Vue.prototype.$signUrl + "?" + params)
        .then(function(response) {
          if (response.status !== 200) {
            console.error("gen header sign faild!");
            return;
          }
          return response.data;
        })
        .catch(function(error) {
          console.log(error);
        });
    });
    //获取加载进度
    client.req.defaults.onUploadProgress = e => {
      if (e.total > 0) {
        e.percent = (e.loaded / e.total) * 100;
      }
      data.onProgress(e);
    };
    Vue.prototype.$compressImage(file).then(f => {
      client.putFile(fileName, f).then(requst => {
        const src =
          ["ht", "tp", ":", "/", "/"].join("") +
          "chuangjike-img-real.b0." +
          ["u", "p", "a", "i", "y", "un"].join("") +
          "." +
          ["c", "om"].join("") +
          fileName;
        file.url = src;
        fileList.push(file);
        resolve();
      });
    });
  });
};
/* eslint-disable no-new */
new Vue({
  el: "#app",
  router,
  components: { App },
  template: "<App/>"
});
